package com.syl.orm.autoconfigure;

import com.syl.orm.spring.EsMapperFactoryBean;
import com.syl.orm.spring.EsMapperScannerConfigurer;
import com.syl.orm.ibatis.SqlSessionFactory;
import com.syl.orm.ibatis.SqlSessionFactoryBuilder;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotationMetadata;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;

/**
 * @Description:
 * @author: YunLong
 * @date: 2022-08-31 09:13
 **/
@Configuration
@ConditionalOnClass({SqlSessionFactory.class})
@EnableConfigurationProperties(EsbatisProperties.class)
public class EsbatisAutoConfiguration implements InitializingBean {


    @Bean
    @ConditionalOnMissingBean
    public SqlSessionFactory esSqlSessionFactory(EsbatisProperties esbatisProperties) throws Exception {
        return new SqlSessionFactoryBuilder().build( esbatisProperties);
    }


    @Configuration
    @Import(EsAutoConfiguredMapperScannerRegistrar.class)
    @ConditionalOnMissingBean({EsMapperFactoryBean.class, EsMapperScannerConfigurer.class})
    public static class MapperScannerRegistrarNotFoundConfiguration implements InitializingBean {

        @Override
        public void afterPropertiesSet() {
        }

    }

    public static class EsAutoConfiguredMapperScannerRegistrar implements EnvironmentAware, ImportBeanDefinitionRegistrar {

        private String basePackage;

        @Override
        public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
            BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(EsMapperScannerConfigurer.class);
            builder.addPropertyValue("basePackage", basePackage);
            registry.registerBeanDefinition(EsMapperScannerConfigurer.class.getName(), builder.getBeanDefinition());
        }

        @Override
        public void setEnvironment(Environment environment) {
            this.basePackage = environment.getProperty("esBatis.es-base-dao-package");
        }
    }


    @Override
    public void afterPropertiesSet() throws Exception {
    }


}
